using Microsoft.Extensions.Options;
using Senparc.CO2NET;
using Senparc.CO2NET.RegisterServices;
using Senparc.Weixin;
using Senparc.Weixin.Entities;
using Senparc.Weixin.RegisterServices;
using WeWorkApp.Api.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// 添加 CORS 支持
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigins", policy =>
    {
        var allowedOrigins = builder.Configuration.GetSection("ApiSettings:AllowedOrigins").Get<string[]>() ?? new[] { "*" };
        policy.WithOrigins(allowedOrigins)
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials();
    });
});

// 配置 Senparc
builder.Services.Configure<SenparcSetting>(
    builder.Configuration.GetSection("SenparcSetting"));

// 配置 Senparc.Weixin
builder.Services.Configure<SenparcWeixinSetting>(
    builder.Configuration.GetSection("SenparcWeixinSetting"));

// 注册 Senparc.Weixin 服务
builder.Services.AddSenparcWeixinServices(builder.Configuration);

// 注册自定义服务
builder.Services.AddScoped<IWeChatWorkService, WeChatWorkService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

// 启用 CORS
app.UseCors("AllowSpecificOrigins");

// 启用 Senparc.Weixin 配置
var senparcSetting = app.Services.GetRequiredService<IOptions<SenparcSetting>>().Value;
var senparcWeixinSetting = app.Services.GetRequiredService<IOptions<SenparcWeixinSetting>>().Value;

// 使用 Senparc.Weixin 注册
var register = RegisterService.Start(senparcSetting)
    .UseSenparcGlobal()
    .UseSenparcWeixin(senparcWeixinSetting);

app.UseAuthorization();

app.MapControllers();

// 添加静态文件支持（用于前端文件）
app.UseStaticFiles();

// 添加默认路由到前端页面
app.MapFallbackToFile("index.html");

app.Run();